<html>

<head>
<title>cargar persona</title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">

<script type="text/javascript" src="js/glMatrix-0.9.5.min.js"></script>
<script type="text/javascript" src="js/webgl-utils.js"></script>
<script type="text/javascript" src="disenos.js"></script>
<script id="shader-fs" type="x-shader/x-fragment">
    #ifdef GL_ES
    precision highp float;
    #endif

  varying vec4 vColor;

  void main(void) {
    gl_FragColor = vColor;
  }
</script>

<script id="shader-vs" type="x-shader/x-vertex">
    attribute vec3 aVertexPosition;
	attribute vec4 aVertexColor;

    uniform mat4 uMVMatrix;
    uniform mat4 uPMatrix;
	
	varying vec4 vColor;

    void main(void) {
        gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
		vColor = aVertexColor;
    }
</script>


<script type="text/javascript">

	
    var gl;
    function initGL(canvas) {
        try {
            gl = canvas.getContext("experimental-webgl");
            gl.viewportWidth = canvas.width;
            gl.viewportHeight = canvas.height;
        } catch (e) {
        }
        if (!gl) {
            alert("Could not initialise WebGL, sorry :-(");
        }
    }


    function getShader(gl, id) {
        var shaderScript = document.getElementById(id);
        if (!shaderScript) {
            return null;
        }

        var str = "";
        var k = shaderScript.firstChild;
        while (k) {
            if (k.nodeType == 3) {
                str += k.textContent;
            }
            k = k.nextSibling;
        }

        var shader;
        if (shaderScript.type == "x-shader/x-fragment") {
            shader = gl.createShader(gl.FRAGMENT_SHADER);
        } else if (shaderScript.type == "x-shader/x-vertex") {
            shader = gl.createShader(gl.VERTEX_SHADER);
        } else {
            return null;
        }

        gl.shaderSource(shader, str);
        gl.compileShader(shader);

        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            alert(gl.getShaderInfoLog(shader));
            return null;
        }

        return shader;
    }


    var shaderProgram;

    function initShaders() {
        var fragmentShader = getShader(gl, "shader-fs");
        var vertexShader = getShader(gl, "shader-vs");

        shaderProgram = gl.createProgram();
        gl.attachShader(shaderProgram, vertexShader);
        gl.attachShader(shaderProgram, fragmentShader);
        gl.linkProgram(shaderProgram);

        if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
            alert("Could not initialise shaders");
        }

        gl.useProgram(shaderProgram);

        shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
        gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);

		 shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor");
    gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);
		
        shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
        shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
    }


    var mvMatrix = mat4.create();
    var pMatrix = mat4.create();

    function setMatrixUniforms() {
        gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);
        gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);
    }



    var triangleVertexPositionBuffer;
    var squareVertexPositionBuffer;
	
	var lista=[];
  
	
	function initBuffers() {

	var cuerpo= new Cuerpo(90,90,90);
	lista.push(cuerpo);
	
    }

	var mundo=null;
	function  loadWorld() {
        var request = new XMLHttpRequest();
        request.open("GET", "./monte3.txt");
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                mundo = new CargarMundo(request.responseText,300);	
				mundo.temp="hola";
            }
        }

		request.send();	
    } 
	

	var currentlyPressedKeys = {};

    function handleKeyDown(event) {
        currentlyPressedKeys[event.keyCode] = true;
    }


    function handleKeyUp(event) {
        currentlyPressedKeys[event.keyCode] = false;
    }

	var pitch = 0;
    var pitchRate = 0;

    var yaw = 0;
    var yawRate = 0;

	var roll = 0;
	var rollRate=0;

    var xaw=0;
    var xawRate=0;

    var xPos = 0;
    var yPos = 0.4;
    var zPos = 0;

    var speed = 0;
    var estado = "normal";
function handleKeys() {
		/*IZQUIERDA - DERECHA*/
		if (currentlyPressedKeys[87]) {
            // KEY W
            speed = 0.03;
			estado = "acelerar";
			
        } else if (currentlyPressedKeys[83]) {
           // KEY S
           speed = 0;
        } else {
            speed = 0;
			estado = "normal";
        }
        if (currentlyPressedKeys[37] ) {
            // Left cursor
            yawRate = 0.05;
            rollRate=-10;
			estado = "doblarIzq";
        } else if (currentlyPressedKeys[39]) {
            // Right cursor
            yawRate = -0.05;
            rollRate=10;
			estado = "doblarDer";
        } else {
            yawRate = 0;
            rollRate=0;
		
        }

        if (currentlyPressedKeys[38] ) {
        	// Up cursor
            xawRate = -0.1;
			estado = "subir";
        } else if (currentlyPressedKeys[40]) {
            // Down cursor
            xawRate = 0.1;
			estado = "acelerar";
        } else {
            xawRate = 0;
		
        }

    }


    var lastTime = 0;

     function degToRad(degrees) {
        return degrees * Math.PI / 180;
    }

var elapsed;
    function animate() {
        var timeNow = new Date().getTime();
        if (lastTime != 0) {
            elapsed = timeNow - lastTime;

            if (speed != 0) {
                xPos -= Math.sin(degToRad(yaw)) * speed * elapsed;
                zPos -= Math.cos(degToRad(yaw)) * speed * elapsed;

				yPos -= 0.1 * speed;

            }

            	xPos -= Math.sin(degToRad(yaw)) * 0.01 * elapsed;
                zPos -= Math.cos(degToRad(yaw)) * 0.01  * elapsed;
            	
				yPos -= 0.0008  * elapsed;

			roll=rollRate;

            yaw += yawRate * elapsed;
            xaw +=xawRate  * elapsed;
            pitch += pitchRate * elapsed;

        }
        lastTime = timeNow;
    }

	function posCuerpo(cuerpo, posicion){
	
		if(posicion=="doblarDer"){
			 cuerpo.anguloBrazoIzq=10;
			 cuerpo.anguloBrazoDer=60;
			 cuerpo.anguloPierna=0;
			
		}else if(posicion=="doblarIzq"){
			 cuerpo.anguloBrazoIzq=60;
			 cuerpo.anguloBrazoDer=10;
			 cuerpo.anguloPierna=0;
		}else if(posicion=="normal"){
			 cuerpo.anguloBrazoIzq=40;
			 cuerpo.anguloBrazoDer=40;
			 cuerpo.anguloPierna=20;
		
		}else if(posicion=="acelerar"){
			 cuerpo.anguloBrazoIzq=30;
			 cuerpo.anguloBrazoDer=30;
			 cuerpo.anguloPierna=0;
		}else if(posicion=="subir"){
			 cuerpo.anguloBrazoIzq=5;
			 cuerpo.anguloBrazoDer=5;
			 cuerpo.anguloPierna=60;
		}
	
	
	}
	
	function tick() {
        requestAnimFrame(tick);
        handleKeys();
        drawScene();
        animate();
    }
	
	
 function drawScene() {

        gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
		
        mat4.perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 1000.0, pMatrix);	
       
		
		mvPushMatrix();
		mat4.identity(mvMatrix);
		
		mat4.translate(mvMatrix, [0, -0.3, -4]);
		mat4.rotate(mvMatrix,degToRad(15), [1, 0, 0]);
		var i;
    	for(i=0; i<lista.length; i++){
		 mvPushMatrix();
		 mat4.scale(mvMatrix,[0.2,0.2,0.2]); 
		 posCuerpo(lista[i],estado);
	     lista[i].draw();	
		 
		 mvPopMatrix();
		}
	
        mat4.rotate(mvMatrix, degToRad(-pitch), [1, 0, 0]);
        mat4.rotate(mvMatrix, degToRad(-xaw), [1, 0, 0]);
        mat4.rotate(mvMatrix, degToRad(-yaw), [0, 1, 0]);
        mat4.rotate(mvMatrix, degToRad(roll), [0, 0, 1]);
        mat4.translate(mvMatrix, [-xPos, -yPos, -zPos]);

		
	

		

		 mat4.scale(10,500,30); 	
		 if(mundo!=null)
		 mundo.draw();
		mvPopMatrix();
}

		
    function webGLStart() {
        var canvas = document.getElementById("lesson01-canvas");
        initGL(canvas);
        initShaders();
        initBuffers();
		loadWorld();
   

        gl.clearColor(0.1, 0.1, 0.1, 0.5);
        gl.enable(gl.DEPTH_TEST);
		document.onkeydown = handleKeyDown;
        document.onkeyup = handleKeyUp;

        tick();
    }


</script>

</head>


<body onload="webGLStart();">
    <canvas id="lesson01-canvas" style="border: none;" width="500" height="500"></canvas>
</body>
</html>
